import {
  Controller,
  HttpStatus,
  Post,
  Request,
  Get, Render,
  Res,
  Req,
  Headers,
} from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import { LoginService } from '../services';
import { Response } from 'express';
@Controller('auth')
export class LoginController {
  constructor(private readonly loginServive: LoginService
  ) { }

  @Post('login')
  async login(@Request() req, @Res({ passthrough: true }) res: Response) {
    if (req.body.username !== 'ljq' || req.body.password !== '123456') {
      return {
        statusCode: HttpStatus.BAD_REQUEST,
        message: '用户名或密码错误',
      };
    }
    const redirectUrl = req.query.redirect
    const token = uuid()
    let expiryDate: Date
    try {
      await this.loginServive.login(token)
      expiryDate = new Date(Date.now() + 60 * 1000); // 设置过期时间为当前时间往后 10 秒
      res.cookie('token', token, { expires: expiryDate });
    } catch (error) {
      return {
        statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '登录失败',
      };
    }
    console.log(redirectUrl);
    return {
      statusCode: HttpStatus.OK,
      message: '登录成功',
      data: {
        access_token: token,
        redirectUrl,
        expiryDate: expiryDate.getTime()
      }
    };
  }

  @Get('checkToken')
  async checkToken(@Req() req, @Headers() head) {
    console.log(head.authorization);

    const token = head.authorization || req.cookies.token
    const accessToken = await this.loginServive.getAccessToken(token)
    if (!accessToken) {
      return {
        statusCode: HttpStatus.UNAUTHORIZED,
        message: '验证失败',
        redirect: '/api/auth/login'
      };
    }
    const expiredTime = new Date(accessToken.expired_at).getTime()
    if (expiredTime > new Date().getTime()) {
      return {
        statusCode: HttpStatus.OK,
        message: '验证成功',
        data: {
          access_token: token,
          expiryDate: expiredTime
        }
      };
    } else {
      return {
        statusCode: HttpStatus.UNAUTHORIZED,
        message: '验证失败',
        redirect: '/api/auth/login'
      };
    }

  }

  @Get('login')
  // 2.配置ejs文件路径
  @Render('login/index')
  renderLogin() {
    // 3.配置内容
    return { "name": "张三" };
  }

}
